<script lang="ts">
import { Vue, Prop, Component, Watch } from "vue-property-decorator";
import { http, baseUrl } from "@/http";
import draggable from "vuedraggable";
// import Sortable from "sortablejs";
import { operation } from "@/operation";

import Feature from "ol/Feature";
import Polygon from "ol/geom/Polygon";
import MultiPolygon from "ol/geom/MultiPolygon";
import ImageCanvasSource from "ol/source/ImageCanvas";
import Static from "ol/source/ImageStatic";
import WKT from "ol/format/WKT";
import GeoJSON from "ol/format/GeoJSON";
import ImageLayer from "ol/layer/Image";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import * as turf from "@turf/turf";

@Component({ components: { draggable } })
export default class resultList extends Vue {
  @Prop() map: any;
  myArray: any[] = [];

  myArray2: any[] = [];
  created() {}
  mounted() {
    // this.initDrag();
  }
  // initDrag() {
  //   // var els: any = document.querySelectorAll(".ant-table-body");
  //   // els[0].style.maxHeight = els[1].style.maxHeight = "calc(50vh - 116px)";
  //   var el0 = document.querySelectorAll(".myArrayTbody")[0];
  //   var sortable0 = new Sortable(el0, {
  //     animation: 150,
  //     group: { name: "shared", pull: true },
  //     handle: ".handleDrag",
  //     dragClass: "sortable-drag",
  //     removeCloneOnHide: true,
  //     onEnd: (evt: any) => {
  //       console.log(evt.from);
  //       this.reorderImages(evt);
  //     },
  //     onAdd: (/**Event*/ evt: any) => {
  //       this.acrossList(evt); // same properties as onEnd
  //     },
  //   });
  //   var el1 = document.querySelectorAll(".myArrayTbody2")[0];
  //   var sortable1 = new Sortable(el1, {
  //     animation: 150,
  //     group: { name: "shared", pull: true },
  //     handle: ".handleDrag",
  //     removeCloneOnHide: true,
  //   });
  // }

  async search(condition: object, callback: Function) {
    const imageLayer = operation.getLayerById(operation.map, "imgLayer");
    if (imageLayer) {
      operation.map.removeLayer(imageLayer);
      // operation.map.removeLayer(
      //   operation.getLayerById(operation.map, "imageBoxs")
      // );
    }

    console.log(condition);
    this.myArray2 = [];
    this.myArray = [];
    await this.getData(condition);
    callback();
    await this.addImagesToMap();
  }
  removeAllcilayer() {
    let arr = JSON.parse(JSON.stringify(this.map.layerIds));
    arr.map((item: any) => {
      if (item.includes("cilayer")) {
        this.map.removeLayer(this.map.getLayer(item));
      }
    });
  }
  getData(condition: object) {
    return new Promise((resolve) => {
      http
        .post(baseUrl + "/api/image/queryImage", condition)
        // .get("/assets/lib/data.json")
        .then((res) => {
          if (res["code"] == 200) {
            for (let item of res["data"].list) {
              item.ifShow = item.flag ? true : false;
              if (item.flag) this.myArray.push(item);
              else this.myArray2.push(item);
            }
            resolve(true);
          }
        });
    });
  }
  async addImagesToMap() {
    let newPolygon: any;
    for (let obj of this.myArray) {
      obj["boundary"] = new WKT().readGeometry(obj.boundary, {
        dataProjection: "EPSG:4326",
        featureProjection: "EPSG:3857",
      });

      const newFe = new Feature({
        ...obj,
      });

      //
      obj.url = "http://192.168.0.202:8081/quickView/" + obj.quickViewUrl;
      newFe.setGeometryName("boundary");
      const img = new Image();
      img.src = obj.url;
      await new Promise((resolve) => {
        img.onload = function () {
          resolve(true);
        };
      });

      obj.img = img;
      // operation.addGraphicsToLayer(operation.map, {
      //   clearBefore: false,
      //   geometrys: [obj["boundary"]],
      //   layerId: "imageBoxs",
      //   style: undefined,
      // });
    }
    operation.map.addLayer(new ImageLayer({ id: "imgLayer" }));
    operation.getLayerById(operation.map, "drawLayer").setZIndex(10);
    // operation.map
    //   .getLayers()
    //   .setAt(10, operation.getLayerById(operation.map, "drawLayer"));
    this.addImageLayers();
  }
  addImageLayers(id?: string) {
    const list = id ? this.tepmImgList : this.myArray,
      map = operation.map,
      layerId = id || "imgLayer";
    var imgLayer = operation.getLayerById(operation.map, layerId);
    var imgSource = new ImageCanvasSource({
      ratio: 1,
      canvasFunction: function (
        extent: any,
        resolution: any,
        ratio: any,
        size: any,
        Projection: any
      ) {
        var canvas = document.createElement("canvas");
        canvas.setAttribute("width", size[0]);
        canvas.setAttribute("height", size[1]);
        var context: any = canvas.getContext("2d");

        for (let i = list.length - 1; i >= 0; i--) {
          const item = list[i];
          if (!item.ifShow) {
            continue;
          }
          const exentTopLeft = [extent[0], extent[3]];
          const [[p1, p2, p3, p4]] = item.boundary.getCoordinates();
          const [pxp1, pxp2, pxp3, pxp4] = [
            map.getPixelFromCoordinate(p1),
            map.getPixelFromCoordinate(p2),
            map.getPixelFromCoordinate(p3),
            map.getPixelFromCoordinate(p4),
          ];
          const pxExent = map.getPixelFromCoordinate(exentTopLeft);
          const tan1 = (p2[1] - p1[1]) / (p2[0] - p1[0]);
          const tan2 = (p4[0] - p1[0]) / (p4[1] - p1[1]);
          const p1Top2 = pxp2[0] - pxp1[0];
          const p1Top4 = pxp4[1] - pxp1[1];
          context?.setTransform(
            1,
            -tan1,
            -tan2,
            1,
            pxp1[0] - pxExent[0],
            pxp1[1] - pxExent[1]
          );
          context?.drawImage(item.img, 0, 0, p1Top2, p1Top4);
        }
        return canvas;
      },
    });
    imgLayer.setSource(imgSource);
  }

  tepmImgList: any = [];

  async clickAddImage(item: any, which?: string) {
    item.ifShow = !item.ifShow;

    which = which || "t1";
    if (which == "t1") {
      this.addImageLayers();
      return;
    }
    const t = this.tepmImgList.find((v: any) => item.entityId == v.entityId);

    if (which == "t2" && item.ifShow) {
      var tepmImgLayer = operation.getLayerById(operation.map, "tepmImgLayer");

      if (!tepmImgLayer) {
        operation.map.addLayer(new ImageLayer({ id: "tepmImgLayer" }));
      }
      if (t) {
        t.ifShow = item.ifShow;
        this.addImageLayers("tepmImgLayer");
        return;
      }
      if (item.img) {
        this.tepmImgList.push(item);
        this.addImageLayers("tepmImgLayer");
        return;
      }
      const obj = item;
      obj["boundary"] = new WKT().readGeometry(obj.boundary, {
        dataProjection: "EPSG:4326",
        featureProjection: "EPSG:3857",
      });

      const newFe = new Feature({
        ...obj,
      });

      //
      obj.url = "http://192.168.0.202:8081/quickView/" + obj.quickViewUrl;
      newFe.setGeometryName("boundary");
      const img = new Image();
      img.src = obj.url;
      await new Promise((resolve) => {
        img.onload = function () {
          resolve(true);
        };
      });

      obj.img = img;
      console.log(obj);
      this.tepmImgList.push(obj);

      this.addImageLayers("tepmImgLayer");
    } else if (which == "t2" && !item.ifShow) {
      t.ifShow = false;
      this.addImageLayers("tepmImgLayer");
    }

    // if (!item.ifShow) {
    //   const layer = this.map.getLayer("cilayer" + item.entityId);
    //   if (which == "t2") {
    //     this.map.removeLayer(layer);
    //   } else {
    //     layer.hide();
    //   }
    // } else this._addimage2map(item);
  }
  dragOptions = {
    animation: 150,
    group: "description",
    handle: ".handleDrag",
  };
  onEnd(evt: any) {
    if (evt.to.id == "t2") {
      const item = this.myArray2[evt.newIndex];
      item.ifShow = false;
      this.addImageLayers();
      return;
    }
    this.addImageLayers();
  }

  async onAdd(evt: any) {
    let obj = this.myArray[evt.newIndex];
    obj.ifShow = true;
    if (obj.img) {
      this.addImageLayers();
      this.tepmImgList = this.tepmImgList.filter((i: any) => {
        i.entityId != obj.entityId;
      });
      this.addImageLayers("tepmImgLayer");

      return;
    }
    obj["boundary"] = new WKT().readGeometry(obj.boundary, {
      dataProjection: "EPSG:4326",
      featureProjection: "EPSG:3857",
    });

    const newFe = new Feature({
      ...obj,
    });

    //
    obj.url = "http://192.168.0.202:8081/quickView/" + obj.quickViewUrl;
    newFe.setGeometryName("boundary");
    const img = new Image();
    img.src = obj.url;
    await new Promise((resolve) => {
      img.onload = function () {
        resolve(true);
      };
    });

    obj.img = img;
    this.addImageLayers();
  }
  ifShowModal = false;
  tableModalData = {};
  showModal(item: any) {
    this.ifShowModal = true;
    const {
      entityId,
      acquireTime,
      satelliteId,
      sensorId,
      resolution,
      cloudCover,
      quickViewUrl,
    } = item;

    this.tableModalData = JSON.parse(
      JSON.stringify({
        entityId,
        acquireTime,
        satelliteId,
        sensorId,
        resolution,
        cloudCover,
        quickViewUrl,
      })
    );
    console.log(item);
  }
  showCoverageArea(item: any) {
    function correct(coordinates: any) {
      const [[p1, p2, p3, p4]] = coordinates;
      let x = p4[0] - (p1[0] - p2[0]);
      let y = p4[1] - (p1[1] - p2[1]);
      return [[p1, p2, [x, y], p4, p1]];
    }

    operation.addGraphicsToLayer(operation.map, {
      geometrys: [new Polygon(correct(item.boundary.getCoordinates()))],
      layerId: "coverBox",
      clearBefore: true,
      style: operation.createSymbol("#00000000", 1, "#ffff00ff"),
    });
  }
}
</script>

<template>
  <div id="resultList">
    <div class="tableBox">
      <table class="headeTable">
        <tr>
          <th>操作</th>
          <th>卫星</th>
          <th>成像时间</th>
          <th>分辨率(m)</th>
          <th>云量(%)</th>
        </tr>
      </table>
      <draggable
        tag="table"
        id="myArray"
        v-model="myArray"
        v-bind="dragOptions"
        @end="onEnd"
        @add="onAdd"
      >
        <transition-group type="transition" name="shared" tag="tbody">
          <tr
            v-for="(item) of myArray"
            :id="`${item.entityId}`"
            :key="item.entityId"
            @mouseenter="showCoverageArea(item)"
          >
            <td class="ImageOpera">
              <a-icon
                type="eye"
                :style="{ color: item.ifShow ? '#1890ff' : '' }"
                @click="clickAddImage(item)"
              />
              <a-icon type="drag" class="handleDrag" />
              <a-icon type="more" @click="showModal(item)" />
            </td>
            <td>{{item.satelliteId}}</td>
            <td>{{item.acquireTime}}</td>
            <td>{{item.resolution}}</td>
            <td>{{item.cloudCover}}</td>
          </tr>
        </transition-group>
      </draggable>
    </div>
    <div style="height:20px;background:#ececec">回收池</div>
    <div class="tableBox">
      <table class="headeTable">
        <tr>
          <th>操作</th>
          <th>卫星</th>
          <th>成像时间</th>
          <th>分辨率(m)</th>
          <th>云量(%)</th>
        </tr>
      </table>
      <draggable tag="table" id="myArray2" v-model="myArray2" v-bind="dragOptions">
        <transition-group type="transition" tag="tbody" id="t2" name="no">
          <tr v-for="(item) of myArray2" :id="`${item.entityId}`" :key="item.entityId">
            <td class="ImageOpera">
              <a-icon
                type="eye"
                :style="{ color: item.ifShow ? '#1890ff' : '' }"
                @click="clickAddImage(item,'t2')"
              />
              <a-icon type="drag" class="handleDrag" />
              <a-icon type="more" @click="showModal(item)" />
            </td>
            <td>{{item.satelliteId}}</td>
            <td>{{item.acquireTime}}</td>
            <td>{{item.resolution}}</td>
            <td>{{item.cloudCover}}</td>
          </tr>
        </transition-group>
      </draggable>
      <!-- </table> -->
    </div>
    <a-modal
      :title="null"
      :footer="null"
      :visible="ifShowModal"
      @cancel="ifShowModal=false"
      :width="'60vw'"
    >
      <!-- <p style="height:80vh;">{{ ModalText }}</p> -->
      <div id="modalBox">
        <div id="imgBox">
          <img :src="'http://192.168.0.202:8081/quickView/'+tableModalData.quickViewUrl" alt />
        </div>
        <table>
          <tr v-for="(item,key) in tableModalData" :key="item">
            <td>{{key}}</td>
            <td>{{item}}</td>
          </tr>
        </table>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
#resultList {
  height: calc(100vh - 95px);
  margin-top: -13px;
  width: 100%;
  overflow: auto;

  .tableBox {
    height: calc(50% - 10px);
    box-sizing: border-box;
    overflow: auto;
    // overflow-y: hidden;
    // overflow-x: scroll;

    width: 100%;
  }

  .item {
    height: 30px;
    border-bottom: 1px solid #a00;
    cursor: pointer;
  }
  #myArray2,
  #myArray {
    width: 100%;
    min-width: 400px;

    text-align: center;
    .sortable-drag {
      background-color: cyan;
    }
    tr {
      border-bottom: #eaeaea solid 1px;
      .ImageOpera {
        i {
          margin: 0 3px;
          cursor: pointer;
        }
        .handleDrag {
          cursor: move;
        }
      }
      td {
        font-size: 14px;
        font-weight: normal;
        padding: 3px 0;
        color: rgba(#000, 0.65);
      }
      td:nth-child(1) {
        width: 17%;
      }
      td:nth-child(2) {
        width: 15%;
      }
      td:nth-child(3) {
        width: 35%;
      }
      td:nth-child(4) {
        width: 18%;
      }
      td:nth-child(5) {
        width: 15%;
      }
    }
  }
  table.headeTable {
    width: 100%;
    min-width: 400px;
    text-align: center;
    th {
      color: rgba(#000, 0.85);
      font-size: 14px;
      font-weight: normal;
      border-bottom: #eaeaea solid 1px;
      padding: 3px 0;
    }
    th:nth-child(1) {
      width: 17%;
    }
    th:nth-child(2) {
      width: 15%;
    }
    th:nth-child(3) {
      width: 35%;
    }
    th:nth-child(4) {
      width: 18%;
    }
    th:nth-child(5) {
      width: 15%;
    }
  }
}
#modalBox {
  // height: 80vh;
  // display: flex;
  overflow: hidden;
  #imgBox {
    float: left;
    width: 70%;
    height: 100%;
    text-align: center;
    background-color: #eaeaea;
    img {
      max-width: 100%;
      max-height: 80vh;
    }
  }
  table {
    width: 30%;
    float: left;
    max-height: 80vh;
    border: 1px solid #aaa;
    border-collapse: collapse;
    td {
      border: 1px solid #aaa;
      word-break: break-all;
      width: 50%;
    }
  }
}
</style>
